<template>
	<view>
		<view class='calendar'>
			<!--显示当前年月日-->
			<view class='calendar-title'>
				<view class='item title'>
					<view class='ctrl' @tap='lastMonth1'>{{lastMonth}}</view>
					<view>{{title}}</view>
					<view class='ctrl' @tap='nextMonth1'>{{nextMonth}}</view>
				</view>
				<view class='item ctrl today' @tap='switchFg'>{{switchtext}}</view>
				<view class='item ctrl today' @tap='today'>回到今天</view>
			</view>
		
			<!-- ============滚动展示============  -->
			<view v-show="toggleType == 'large'">
				<scroll-view :scroll-left="scrollLeft" scroll-x scroll-with-animation class="calendar-x">
					<view class='grid' v-for='item in thisMonthDays' >
						<view class='self' v-if="format == year+'-'+item.monthFormat+'-'+item.dateFormat"></view>
						<view :class="select == year+'-'+item.monthFormat+'-'+item.dateFormat ? 'select wrap' :'wrap' " @tap='selectdate' :data-date='item.date'>{{item.date}}</view>
					</view>
				</scroll-view>
			</view>
		
			<!-- ============平铺展示============  -->
			<!--遍历星期-->
			<view class='calendar-week' v-show="toggleType == 'mini'">
				<view v-for='item in weekText' class='item'>{{item}}</view>
			</view>
		
			<view class='calendar-container' v-show="toggleType == 'mini'">
				<!--上个月占位格子-->
				<view class='grid gray' v-for='item in empytGridsBefore'>{{item}}</view>
		
				<!--当月格子-->
				<view class='grid' v-for='item in thisMonthDays' >
					<view class='self' v-if="format == year+'-'+item.monthFormat+'-'+item.dateFormat"></view>
					<view :class="select == year+'-'+item.monthFormat+'-'+item.dateFormat ? 'wrap select' :'wrap' " @tap='selectdate' :data-date='item.date'>{{item.date}}</view>
				</view>
		
				<!--下个月占位格子-->
				<view class='grid gray' v-for='item in empytGridsAfter'>{{item}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "jiangyanCalendar",
		props: {
			defaultValue: {
			    type: String,
			    value: ''
			},
			//星期数组
			weekText: {
			    type: Array,
			    default: ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
			},
			lastMonth: {
			    type: String,
			    default: '◀'
			},
			nextMonth: {
			    type: String,
			    default: '▶'
			},
			// toggleType: {
			// 	type:String,
			// 	default:'large'
			// },
		},
		//初始默认为当前日期
		data() {
			return {
				//当月格子
				thisMonthDays: [],
				//上月格子
				empytGridsBefore: [],
				//下月格子
				empytGridsAfter: [],
				//显示日期
				title: '',
				//格式化日期
				format: '',
				year: 0,
				month: 0,
				date: 0,
				toggleType:'large',
				scrollLeft: 0,
				//常量 用于匹配是否为当天
				YEAR: 0,
				MONTH: 0,
				DATE: 0,
				format:'',
				select:'',
				switchtext:'展开'
			}
		},
		mounted() {
			this.today();
		},
		methods: {
			//切换展示
			switchFg() {
				this.toggleType = this.toggleType == 'mini' ? 'large' : 'mini';
				this.switchtext = this.toggleType == 'mini' ?'收起':'展开';
			    //初始化日历组件UI
			    this.display(this.year, this.month, this.date);
			},
			//滚动模式
			//当年当月当天 滚动到制定日期 否则滚动到当月1日
			scrollCalendar(year, month, date) {
			    console.log(year, month, date)
			    var scrollLeft = 0;
				var that = this;
			    uni.getSystemInfo({
			        success(res){
			            //切换月份时 date为0
			            if (date == 0) {
			                scrollLeft = 0;
			                //切换到当年当月 滚动到当日
			                if (year == that.YEAR && month == that.MONTH) {
			                    scrollLeft = that.DATE * 45 - res.windowWidth / 2 - 22.5;
			                }
			            } else {
			                // 点选具体某一天 滚到到指定日期
			                scrollLeft = date * 45 - res.windowWidth / 2 - 22.5;
			            }
						that.scrollLeft = scrollLeft;
			        }
			    })
			},
			
			//初始化
			display: function (year, month, date) {
				this.year = year;
				this.month = month;
				this.date = date;
				this.title = year + '年' + this.zero(month) + '月';
			    this.createDays(year, month);
			    this.createEmptyGrids(year, month);
			
			    //滚动模糊 初始界面
			    this.scrollCalendar(year, month, date);
			},
			//默认选中当天 并初始化组件
			today: function () {
			    let DATE = this.defaultValue ? new Date(this.defaultValue) : new Date(),
			        year = DATE.getFullYear(),
			        month = DATE.getMonth() + 1,
			        date = DATE.getDate(),
			        select = year + '-' + this.zero(month) + '-' + this.zero(date);
				this.format = select;
				this.select = select;
				this.year = year;
				this.month = month;
				this.date = date;
				this.YEAR = year;
				this.MONTH = month;
				this.DATE = date;
			    //初始化日历组件UI
			    this.display(year, month, date);
				console.log('初始化组件中今天的日期',select);
				uni.setStorageSync('nowdate',select);
			    //发送事件监听
			    this.$emit('selectedday', select);
			},
			
			//选择 并格式化数据
			selectdate: function (e) {
			    let date = e.currentTarget.dataset.date,
			        select = this.year + '-' + this.zero(this.month) + '-' + this.zero(date);
				this.title = this.year + '年' + this.zero(this.month) + '月' + this.zero(date) + '日';
				this.select = select;
				this.year = this.year;
				this.month = this.month;
				this.date = date;
				console.log('组件中当前选中的日期',select);
				uni.setStorageSync('nowdate',select);
			    //发送事件监听
			    this.$emit('selectedday', select);
			
			    //滚动日历到选中日期
			    this.scrollCalendar(this.year, this.month, date);
			},
			//上个月
			lastMonth1: function () {
			    let month = this.month == 1 ? 12 : this.month - 1;
			    let year = this.month == 1 ? this.year - 1 : this.year;
			    //初始化日历组件UI
			    this.display(year, month, 0);
			},
			//下个月
			nextMonth1: function () {
			    let month = this.month == 12 ? 1 : this.month + 1;
			    let year = this.month == 12 ? this.year + 1 : this.year;
			    //初始化日历组件UI
			    this.display(year, month, 0);
			},
			//获取当月天数
			getThisMonthDays: function (year, month) {
			    return new Date(year, month, 0).getDate();
			},
			// 绘制当月天数占的格子
			createDays: function (year, month) {
			    let thisMonthDays = [],
			        days = this.getThisMonthDays(year, month);
					this.thisMonthDays = thisMonthDays;
			    for (let i = 1; i <= days; i++) {
			        this.thisMonthDays.push({
			            date: i,
			            dateFormat: this.zero(i),
			            monthFormat: this.zero(month),
			            week: this.weekText[new Date(Date.UTC(year, month - 1, i)).getDay()]
			        });
			    }
			},
			//获取当月空出的天数
			createEmptyGrids: function (year, month) {
			        //当月天数
			    let thisMonthDays = this.getThisMonthDays(year, month),
			
			        // 求出本月1号是星期几，本月前面空出几天，就是上月的日期
			        // 0（周日） 到 6（周六）
			        before = new Date(Date.UTC(year, month - 1, 1)).getDay(),
			
			        // 后面空出的天数
			        after = 7 - new Date(Date.UTC(year, month - 1, thisMonthDays)).getDay() - 1,
			
			        empytGridsBefore = [],
			        empytGridsAfter = [];
			    //上月天数
			    let preMonthDays = month - 1 < 0 ?
			        this.getThisMonthDays(year - 1, 12) :
			        this.getThisMonthDays(year, month - 1);
			
			    //前面空出日期
			    for (let i = 1; i <= before; i++) {
			        empytGridsBefore.push(preMonthDays - (before - i));
			    }
			
			    // 后面空出的日期
			    for (let i = 1; i <= after; i++) {
			        empytGridsAfter.push(i);
			    }
				this.empytGridsAfter = empytGridsAfter;
				this.empytGridsBefore = empytGridsBefore;
			},
			
			//补全0
			zero: function (i) {
			    return i >= 10 ? i : '0' + i;
			}
		}
	}
</script>

<style>
	.calendar {
	    width: 100%;
	    text-align: center;
	    font-size: 30rpx;
	    box-sizing: border-box;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
	}
	
	/* 标题 */
	
	.calendar-title {
	    display: flex;
		justify-content: space-around;
		align-items: center;
	    font-size: 25rpx;
	    text-align: left;
	    padding: 20rpx;
	    box-sizing: border-box;
	}
	
	.calendar-title .ctrl {
	    display: inline-block;
	    padding: 0 20rpx;
	    background: #ff9800ad;
	    border-radius: 10rpx;
	}
	
	.calendar-title .item {
	    display: inline-block;
	    vertical-align: middle;
	    line-height: 50rpx;
	}
	
	.calendar-title .title {
	    width: 50%;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.calendar-title .today {
	}
	
	/* 星期 */
	
	.calendar-week {
	    display: flex;
	    text-align: center;
	    padding: 20rpx 10rpx;
	    box-sizing: border-box;
	    border-top: 1rpx solid #e0e0e0;
	    border-bottom: 1rpx solid #e0e0e0;
	    background: #E91E63;
	        color: #fff;
	}
	
	.calendar-week .item {
	    flex: 1;
	}
	
	/* 日期 */
	
	.calendar-container {
		border: 1rpx #ddd dashed;
	    display: flex;
	    flex-wrap: wrap;
	    padding: 20rpx 10rpx;
	    box-sizing: border-box;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
	}
	
	.calendar-container .grid {
	    display: inline-block;
	    width: 14.28571428571429%;
	    line-height: 70rpx;
	    position: relative;
	    z-index: 1;
	}
	.calendar-container .grid .wrap{
		
	}
	.calendar-container .grid .self {
	    position: absolute;
	    top: 0rpx;
	    right: 0rpx;
	    width: 15rpx;
	    height: 15rpx;
	    border-radius: 50%;
	    background: rgb(49, 120, 228);
	    border: 3rpx solid #fff;
	}
	
	.calendar-container .gray {
	    color: #ccc;
	}
	
	.calendar-container .grid .select {
	    background: rgb(49, 120, 228);
	    border-radius: 10rpx;
	    color: #fff;
	    width: 80%;
	    margin: 0 auto;
	}
	
	/* 滚动展示 */
	
	.calendar-x {
		height: 75rpx;
		border: 1rpx #ddd dashed;
	    white-space: nowrap;
	    padding: 20rpx 0;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
	}
	
	.calendar-x .grid {
	    display: inline-block;
	    line-height: 70rpx;
	    position: relative;
	    z-index: 1;
	    width: 70rpx;
	    text-align: center;
	    background: #eee;
	    border-radius: 10rpx;
	    margin-left: 20rpx;
	}
	.calendar-x .grid:last-child{
	    margin-right: 20rpx;
	}
	
	.calendar-x .grid .self {
	    position: absolute;
	    top: 0rpx;
	    right: 0rpx;
	    width: 15rpx;
	    height: 15rpx;
	    border-radius: 50%;
	    background: rgb(49, 120, 228);
	    border: 3rpx solid #fff;
	}
	
	.calendar-x .gray {
	    color: #ccc;
	}
	
	.calendar-x .grid .select {
	    background: rgb(49, 120, 228);
	    border-radius: 10rpx;
	    color: #fff;
	    margin: 0 auto;
	}
	
</style>
